package internal

import (
	"errors"
	"wechat-push/config"
	"wechat-push/internal/model"
	"wechat-push/internal/repository"
	"wechat-push/pkg/logger"
)

func GetWechatToken() (token string, err error) {
	resp, err := repository.GetWechatToken(config.Cfg.Wechat.AppId, config.Cfg.Wechat.AppSecret)
	if err != nil {
		err = errors.New("获取token失败，请检查appId和appSecret是否正确")
		return
	}
	token = resp.AccessToken
	return
}

func SendMessage(token, userId, templateId string, data interface{}) (err error) {
	datas := model.WechatMessageDatas{
		ToUser:     userId,
		TemplateId: templateId,
		Data:       data,
	}
	resp, err := repository.SendWechatMessage(token, datas)
	if err != nil {
		logger.Log.Error("SendWechatMessage err :", err)
		return
	}
	switch resp.ErrCode {
	case 40037:
		err = errors.New("推送消息失败，请检查模板id是否正确")
	case 40036:
		err = errors.New("推送消息失败，请检查模板id是否为空")
	case 40003:
		err = errors.New("推送消息失败，请检查微信号是否正确")
	}
	return

}
